import "./styles/index.css";
import "./styles/iconfont.css";
import dayjs from "dayjs";
import { v4 as uuidv4 } from 'uuid';
import { createStyledElement } from './utils'

interface ITodo {
  id: string;
  content: string;
  finished: boolean;
  ctime: number;
  mtime: number;
}

let todoList = new Array<ITodo>();
let compositionStatus = false;
const root = document.getElementById("root");

const initPage = () => {
  readStorage(); // 读取localStorage
  root.innerHTML = ""; // 初始化清空

  // 构建标题
  const header = createStyledElement("header", "logo-header");
  header.innerHTML = "TODO LIST";
  root.appendChild(header);

  // 构建输入框
  const input = createStyledElement("input", "input-submit", "input1");
  input.addEventListener('keydown', keydownHandler);
  input.addEventListener('compositionstart', () => {compositionStatus = true});
  input.addEventListener('compositionend', () => {compositionStatus = false});
  root.appendChild(input);

  // 构建主体容器
  const container = createStyledElement("div", "app-display", "container");
  root.appendChild(container);

  // // 构建footer
  // const footer = createStyledElement("footer", "clear-all-button");
  // const btn = createStyledElement("div", "clearBut", "clearBut");
  // btn.addEventListener('click', clearAllHandler);
  // btn.innerHTML = "清除所有任务";
  // footer.appendChild(btn);
  // root.appendChild(footer);

  updateTasks();
}

const readStorage = () => {
  if(localStorage.getItem('todoList') === null) {
    console.log("初始化localstorage");
    localStorage.setItem('todoList', JSON.stringify(todoList));
  } else {
    console.log("读取localstorage");
    todoList = JSON.parse(localStorage.getItem('todoList'));
  }
}

const writeStorage = () => {
  localStorage.setItem('todoList', JSON.stringify(todoList));
}

const keydownHandler = (e: KeyboardEvent) => {
  if(compositionStatus === true) {
      return;
  }
  const keyCode = e.code;
  const input = document.getElementById("input1") as HTMLInputElement;
  if(keyCode === "Enter" || keyCode === "NumpadEnter") {
      if(input.value === "") {
          return;
      }
      todoList.push({
        id: uuidv4(),
        content: input.value,
        finished: false,
        ctime: dayjs().valueOf(), // 用时间戳存储
        mtime: dayjs().valueOf(),
      })
      input.value = "";
      updateTasks();
  }
}

const deleteHandler = (e: MouseEvent) => {
  const id = (e.target as HTMLElement).parentElement.id;
  const index = todoList.indexOf(todoList.find(item => item.id === id));
  todoList.splice(index, 1); // 删除对应元素
  updateTasks();
}

const finishHandler = (e: MouseEvent) => {
  const id = (e.target as HTMLElement).parentElement.id;
  const target = todoList.find(item => item.id === id);
  if(target.finished === true) {
    target.finished = false;
  } else {
    target.finished = true;
  }
  target.mtime = dayjs().valueOf(); // 更新修改时间
  updateTasks();
}

const clearAllHandler = () => {
  localStorage.clear();
  todoList = new Array<ITodo>();
  updateTasks();
}

const createTodoItem = (data: ITodo) => {
  const elmt = createStyledElement("div", data.finished? "taskElement taskFinished": "taskElement", data.id);

  // 生成勾选框
  const checkIcon = createStyledElement("i", "iconfont iconCheckbox");
  checkIcon.addEventListener('click', finishHandler);
  elmt.appendChild(checkIcon);
  
  // 生成任务文本
  const text = createStyledElement("span", "taskText");
  const title = createStyledElement("span", "taskTile");
  title.innerHTML = data.content;
  text.appendChild(title);
  const time = createStyledElement("span", "taskTime");
  time.innerHTML = dayjs(data.ctime).format('MM月DD日 HH:mm:ss').toString();
  text.appendChild(time);
  elmt.appendChild(text);

  // 生成删除标
  const deleteIcon = createStyledElement("i", "iconfont iconDelete");
  deleteIcon.addEventListener('click', deleteHandler);
  elmt.appendChild(deleteIcon);

  return elmt;
}

const updateTasks = () => {
  writeStorage();
  const container = document.getElementById("container");
  container.innerHTML = "";
  const sec = createStyledElement("section", todoList.length === 0? "congratulation": "displaySection");
  if(todoList.length === 0) {
    sec.innerHTML = "没有任务~";
  }
  else {
    for (let todo of todoList) {
      const todoItem = createTodoItem(todo);
      sec.appendChild(todoItem);
    }
  }
  container.appendChild(sec);
}

window.onload = initPage;